# application/services/system/user.py
from application.mapper.system.user import UserMapper
from typing import Dict, Any
from datetime import datetime
from application.extensions.logging import system_logger

class UserService:
    """用户服务层"""
    
    @staticmethod
    def get_user_page(page_num: int, page_size: int, conditions: Dict[str, Any] = None) -> Dict[str, Any]:
        """
        获取用户分页列表
        :param page_num: 页码
        :param page_size: 每页数量
        :param conditions: 查询条件
        :return: 分页结果
        """
        try:
            # 处理时间参数格式
            if conditions and conditions.get('params'):
                params = conditions.pop('params')
                if params.get('beginTime'):
                    conditions['beginTime'] = datetime.strptime(params['beginTime'], '%Y-%m-%d %H:%M:%S')
                if params.get('endTime'):
                    conditions['endTime'] = datetime.strptime(params['endTime'], '%Y-%m-%d %H:%M:%S')
            
            # 调用数据访问层获取数据
            users, total = UserMapper.get_user_list(page_num, page_size, conditions)
            
            # 转换为字典格式
            user_list = []
            for user in users:
                user_dict = {
                    "userId": user.user_id,
                    "tenantId": user.tenant_id,
                    "deptId": user.dept_id,
                    "userName": user.user_name,
                    "nickName": user.nick_name,
                    "userType": user.user_type,
                    "email": user.email,
                    "phonenumber": user.phonenumber,
                    "sex": user.sex,
                    "avatar": user.avatar,
                    "status": user.status,
                    "loginIp": user.login_ip,
                    "loginDate": user.login_date.strftime('%Y-%m-%d %H:%M:%S') if user.login_date else None,
                    "delFlag": user.del_flag,
                }
                user_list.append(user_dict)
            
            return {
                'rows': user_list,
                'total': total,
                'code': 200,
                'msg': '查询成功'
            }
            
        except Exception as e:
            
            system_logger.error(f"获取用户分页列表失败: {e}")
            return {
                'rows': [],
                'total': 0,
                'code': 500,
                'msg': '查询失败'
            }